﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchoolApplication.Models;
using GameSchoolApplication.Repositories;
using GameSchoolApplication.Classes;
using GameSchoolApplication.Models.ViewModels;
using System.IO;


namespace GameSchoolApplication.Controllers
{
    public class MaterialController : Controller
    {
        //
        // GET: /Material/
        /// <summary>
        /// Gets the view for a particular Material and returns it to the user.
        /// Precondition: The user clicks the Material link
        /// Postcondition: The user has received the Material view
        /// Author: Hlynur
        /// Date: 8.5 
        /// <param name="ID">The ID of the desired Material</param>
        /// <returns>The view  for the Material</returns>
        /// </summary>
        public ActionResult getMaterial(int materialID)
        {
            MaterialRepository rep = new MaterialRepository();
            Material matter = rep.getMaterialByID(materialID);

            return View(matter);
        }

        /// <summary>
        /// Returns the edit Material page for a specific Material. 
        /// Precondition: The user clicks the edit page for the Material in question
        /// Postcondition: The user has recived the edit view for that Material. 
        /// Author: Hlynur
        /// Date:  8.5
        /// </summary>
        public ActionResult editMaterial(int materialID)
        {
            //Initialize the repository
            MaterialRepository rep = new MaterialRepository();
            Material matter = rep.getMaterialByID(materialID);

            return View(matter);
        }

        /// <summary>
        /// TODO: Write a cool-ass description!
        /// As of right now this is just a dummy class 
        /// Precondition:
        /// Postcondition:
        /// Author:
        /// Date: 
        /// </summary>
        [HttpPost]
        public ActionResult editMaterial(Material matter)
        {
            MaterialRepository rep = new MaterialRepository();
            rep.editMaterial(matter);
            return View();
        }

        /// <summary>
        /// Returns the upload lecture form. 
        /// Precondition: The user is a teacher or admin. 
        /// Postcondition: The user has received the add lecture form. 
        /// Author: Krilli
        /// Date: 11.5
        /// </summary>
        /// <param name="levelID"></param>
        /// <returns></returns>
        public ActionResult uploadLecture(int levelID)
        {
            CourseLevelRepository rep = new CourseLevelRepository(); 
            CourseLevel level = rep.getLevelByID(levelID);
            int courseID = level.cID.Value; 
            string userID = getUserIDFromCookie();
            if (isTeacherInCourse(userID, courseID))
            {
                UploadLectureModel newLecture = new UploadLectureModel();
                newLecture.lecture = new Lecture();
                newLecture.lecture.lvlID = levelID;
                return View(newLecture);
            }
            else
            {
                return View("notTeacher");
            }
        }
        
        /// <summary>
        /// Uploads the lecture to the database. 
        /// Precondition: The user has entered the lecture information into the form. 
        /// Postcondition: LEcture has been added to the database. 
        /// Author: Krilli
        /// Date: 11.5
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult uploadLecture(UploadLectureModel model, HttpPostedFileBase file)
        {
            AccountRepository accountRep = new AccountRepository();
            //HttpCookie userInfo = new HttpCookie("userInfo");
            //userInfo = Request.Cookies["userInfo"];
            if (Request.Cookies["userInfo"] == null)
            {
                RedirectToAction("Index", "Home");
            }
            else
            {
                //Upload the file
                Uploader(file);
                LectureRepository lecRep = new LectureRepository();
                Lecture newLecture = new Lecture();
                newLecture.lvlID = model.lecture.lvlID;
                newLecture.name = model.lecture.name;
                newLecture.lectureDesc = model.lecture.lectureDesc;
                newLecture.allowComments = model.lecture.allowComments;
                newLecture.dateOfRecording = DateTime.Now;
                newLecture.filePath = model.videoURL; 

                bool success = lecRep.addLecture(newLecture); 
                if (success)
                {
                    return View("win");
                }
                else
                {
                    return View("fail"); 
                }
            }
            return View();
        }
        
        /// <summary>
        /// Uploader. Uploads the file to the specified path. 
        /// Author: Darin Dimitrov, taken from http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc3-0
        /// </summary>
        /// <param name="file"></param>
        [HttpPost]
        public void Uploader(HttpPostedFileBase file)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }
        }

        /// <summary>
        /// Gets a lecture's view from the database. 
        /// Postcondition: the user has received the lecture. 
        /// Author: Krilli
        /// Date: 11.5 
        /// </summary>
        /// <param name="lectureID"></param>
        /// <returns></returns>
        public ActionResult getLecture(int lectureID)
        {
            LectureRepository lecRep = new LectureRepository();
            Lecture theLecture = lecRep.getLectureByID(lectureID);
            return View(theLecture);
        }


        /// <summary>
        /// skilar lista yfir lectures í level sem Json
        /// precondition:levelID needs to exist in the database
        /// Author: Hlynur
        /// Date: 10.5 
        /// </summary>
        /// <param name="levelID">levelID for the desired lecture.</param>
        /// <returns></returns>
        public ActionResult getLevelLectureList(int levelID)
        {
            LectureRepository rep = new LectureRepository();
            var lectList = (from lecture in rep.getLecturesOfLevel(levelID)
                            select new { lectureID = lecture.lectureID, lectureName = lecture.name, });

            return Json(lectList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Checks if a user is a teacher in a course. 
        /// Precondition: The user is logged in
        /// Postcondition: IF the user is a teacher in the course, a true is returned. 
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="courseID"></param>
        /// <returns></returns>
        public bool isTeacherInCourse(string userID, int courseID)
        {
            AccountRepository rep = new AccountRepository();
            bool retVal = rep.isTeacherInCourse(userID, courseID);
            return retVal;
        }

        /// <summary>
        /// Gets the user ID from the user's cookie. 
        /// Precondition: the user is logged in
        /// Postcondition: The user ID is returned. 
        /// </summary>
        /// <returns></returns>
        public string getUserIDFromCookie()
        {
            string userID = Request.Cookies["userInfo"].Values["userID"];

            return userID;
        }
    }
}
